<template>
  <view class="container">
    <!-- 商店信息 -->
    <view class="store-info">
      <view class="store-name-address">
        <text class="store-name">{{ shopName }}</text>
        <text class="store-address">{{ shopAddress }}</text>
      </view>
    </view>

    <!-- 车型信息 -->
    <view class="car-info" @click="goToCarSelection">
      <text v-if="selectedCar" class="car-details">
        车型: {{ selectedCar.model }} <br />
        车牌号: {{ selectedCar.plate }}
      </text>
      <view v-else>选择车型</view>
    </view>

    <!-- 优惠券选择 -->
    <view class="coupon-info" @click="goToCouponSelection">
      <text v-if="selectedCoupon" class="coupon-details">
        优惠券: {{ selectedCoupon.name }}（-￥{{ selectedCoupon.discountAmount }}）
      </text>
      <view v-else>选择优惠券</view>
    </view>

    <!-- 服务信息 -->
    <view class="service-info">
      <view v-if="selectedServices.length === 0" class="no-services">
        <text>没有选择任何服务</text>
      </view>
      <view v-for="(service, index) in selectedServices" :key="index" class="service-item">
        <view class="service-name-price">
          <text class="service-name">{{ service.name }}</text>
          <text class="service-price">
            原价: ￥{{ service.originalPrice }}  |  折扣价: ￥{{ service.discountPrice }}
          </text>
        </view>
        <view class="service-description">
          <text>{{ service.descriPtion }}</text>
        </view>
      </view>
    </view>

    <!-- 底部按钮行 -->
    <view class="bottom-buttons">
      <view class="total-price">
        <text class="total-text">总计:</text>
        <text class="total-amount">￥{{ finalAmount }}</text>
      </view>
      <button class="submit-order-btn" @click="submitOrder">提交订单</button>
    </view>

    <!-- 支付密码弹窗 -->
    <view v-if="isModalVisible" class="modal-overlay">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">请输入支付密码</text>
        </view>
        <view class="modal-body">
          <text class="total-text">应付金额: ￥{{ finalAmount }}</text>
          <!-- 密码输入框 -->
          <view class="password-input-wrapper">
            <input 
              v-model="password" 
              type="password" 
              maxlength="6" 
              inputmode="numeric" 
              class="password-input" 
              @input="onPasswordInput" />
          </view>
        </view>
        <view class="modal-footer">
          <button @click="submitPayment" class="confirm-btn">确认支付</button>
          <button @click="closeModal" class="cancel-btn">取消</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';

// 订单数据
const shopName = ref('');
const shopAddress = ref('');
const selectedServices = ref([]);
const totalAmount = ref(0);
const selectedCar = ref(null);
const selectedCoupon = ref(null);
const password = ref('');  // 用于存储输入的密码
const isModalVisible = ref(false);  // 控制弹窗的显示

// 计算最终支付金额（考虑优惠券折扣）
const finalAmount = computed(() => {
  if (selectedCoupon.value) {
    return Math.max(0, totalAmount.value - selectedCoupon.value.discountAmount);
  }
  return totalAmount.value;
});

// 获取存储的数据
const loadStoredData = () => {
  selectedCar.value = wx.getStorageSync('selectedCar') || null;
};

// 页面加载时获取参数
onMounted(() => {
  // 获取当前页面栈
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const couponParam = currentPage.options.coupon;

  if (couponParam) {
    try {
      const coupon = JSON.parse(decodeURIComponent(couponParam));
      selectedCoupon.value = coupon;
    } catch (error) {
      console.error('Failed to parse coupon:', error);
    }
  }

  try {
    const orderData = wx.getStorageSync('orderData');
    if (orderData) {
      shopName.value = orderData.shop.name;
      shopAddress.value = orderData.shop.address;
      selectedServices.value = orderData.services;
      totalAmount.value = orderData.totalAmount;
    }
  } catch (e) {
    console.error('订单数据解析失败:', e);
    uni.showToast({ title: '订单数据解析失败，请返回重试', icon: 'none' });
  }

  loadStoredData();
});

// 跳转到选择车型页面
const goToCarSelection = () => {
  uni.navigateTo({ url: '/pages/carwashing/orders/choosecar/choosecar' });
};

// 跳转到选择优惠券页面
const goToCouponSelection = () => {
  uni.navigateTo({ url: '/pages/carwashing/orders/choosecoupon/choosecoupon' });
};

// 提交订单时，显示支付密码弹窗
const submitOrder = () => {
  if (selectedServices.value.length === 0) {
    uni.showToast({ title: '请先选择服务项目', icon: 'none' });
    return;
  }
  if (!selectedCar.value) {
    uni.showToast({ title: '请选择车型', icon: 'none' });
    return;
  }
  isModalVisible.value = true; // 显示支付密码弹窗
};

// 提交支付，验证密码
// 提交支付，验证密码
const submitPayment = () => {
  if (password.value === '123456') {
    uni.showToast({ title: '支付成功', icon: 'success' });
    
    // 将订单信息存入缓存
    const orderDetails = {
      shopName: shopName.value,
      shopAddress: shopAddress.value,
      services: selectedServices.value,
      totalAmount: finalAmount.value,
      car: selectedCar.value,
      coupon: selectedCoupon.value || null,
      orderTime: new Date().toLocaleString(),
    };

    // 使用 uni.setStorageSync 来更新缓存
    uni.setStorageSync('orderDetails', orderDetails);
    
    // 跳转到支付结果页面
    uni.navigateTo({
      url: '/pages/carwashing/payorder/afterpay/afterpay',
      success: () => {
        console.log('跳转到支付结果页面成功');
      },
      fail: (err) => {
        console.error('跳转失败:', err);
      }
    });

    closeModal();  // 关闭密码输入框
  } else {
    uni.showToast({ title: '支付密码错误', icon: 'none' });
  }
};

// 关闭弹窗
const closeModal = () => {
  isModalVisible.value = false;
  password.value = '';  // 清空密码输入框
};

// 密码输入时的处理
const onPasswordInput = (event) => {
  // 限制密码输入为6个字符
  if (event.target.value.length > 6) {
    password.value = password.value.slice(0, 6);
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #f5f5f5;
}
.store-info, .car-info, .coupon-info {
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  cursor: pointer;
}
.car-details, .coupon-details {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}
.bottom-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px 20px;
  box-shadow: 0px -2px 5px rgba(0, 0, 0, 0.1);
}
.total-text {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}
.total-amount {
  font-size: 18px;
  font-weight: bold;
  color: #FF4D4F;
  margin-left: 10px;
}
.submit-order-btn {
  background-color: #FF4D4F;
  color: white;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

/* 自定义支付密码弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}
.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  width: 80%;
  max-width: 350px;
}
.modal-header {
  text-align: center;
  margin-bottom: 20px;
}
.modal-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
.modal-body {
  text-align: center;
}
.password-input-wrapper {
  margin-top: 10px;
}
.password-input {
  width: 80%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 18px;
  letter-spacing: 4px;
  text-align: center;
  font-family: 'Courier New', Courier, monospace;
}
.modal-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
.confirm-btn, .cancel-btn {
  background-color: #FF4D4F;
  color: white;
  padding: 10px;
  border-radius: 5px;
  border: none;
  cursor: pointer;
}
.cancel-btn {
  background-color: #ccc;
}
</style>
